package com.datareport.data.security;

import com.datareport.data.entity.User;
import com.datareport.data.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

   @Autowired
   UserService userService;

   /**
    * 重写底层查找用户的方法，改为从数据库查找用户
    * @param username
    * @return
    * @throws UsernameNotFoundException
    */
   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

      User user = userService.getByName(username);
      if (user == null) {
         throw new UsernameNotFoundException("用户名或密码不正确");
      }
      AccountUser accountUser = new AccountUser(user.getId(), user.getName(), user.getPassword(), getUserAuthority(user.getId()));

      return accountUser;
   }

   /**
    * 获取用户权限信息
    * @param userId
    * @return
    */
   public List<GrantedAuthority> getUserAuthority(Long userId){

      String authority = userService.getUserAuthorityInfo(userId);

      // 通过内置的工具类，把权限字符串封装成GrantedAuthority列表
      List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);

      return grantedAuthorities;
   }
}
